package com.dmall.queue;

/**
 * 带虚拟头结点的链表队列
 * @author xiao1.wang
 * @date 2019-06-29 17:46:29
 * @param <E>
 */
public class DummyHeadLinkedListQueue<E> implements Queue<E> {

    private class Node {
        E e;
        Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node dummyHead, tail;
    private int size;

    public DummyHeadLinkedListQueue() {
        dummyHead = new Node(null, null);
        tail = null;
        size = 0;
    }

    @Override
    public void enqueue(E e) {
        if (tail == null) {
            tail = new Node(e);
            dummyHead.next = tail;
        } else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size ++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Can't dequeue from an empty queue.");
        }
        Node node = dummyHead.next;
        dummyHead.next = node.next;
        node.next = null;
        size --;
        if (dummyHead.next == null) {
            tail = null;
        }
        return node.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Can't getFront from an empty queue.");
        }
        return dummyHead.next.e;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder("Queue: front ");
        Node cur = dummyHead.next;
        while (cur != null) {
            res.append(cur.e).append("->");
            cur = cur.next;
        }
        res.append("NULL tail");
        return res.toString();
    }

    public static void main(String[] args) {
        Queue<Integer> queue = new DummyHeadLinkedListQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);

            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}
